package com.xxx;

import com.xxx.codec.RpcDecoder;
import com.xxx.adapter.ServiceHandlerAdapter;
import com.xxx.registry.ZkUtils;
import com.xxx.registry.ShutdownHook;
import com.xxx.request.RpcRequest;
import com.xxx.serializer.FastJsonSerializer;
import com.xxx.utils.ArgsUtils;
import com.xxx.utils.IpUtils;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.codec.string.StringEncoder;
import org.apache.curator.framework.CuratorFramework;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.data.Stat;
import org.springframework.beans.BeansException;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

@SpringBootApplication
public class ServerBootstrap implements CommandLineRunner, ApplicationContextAware {


    private final static int DEFAULT_PORT = 8991;

    private ApplicationContext applicationContext;

    private int port;


    /**
     * Application Bootstrap
     */
    public static void main(String[] args) {
        SpringApplication.run(ServerBootstrap.class, args);
    }


    @Override
    public void run(String... args) throws Exception {
        /*-设定监听端口-*/
        int port = DEFAULT_PORT;
        if (ArgsUtils.isNotNullOrEmpty(args) && args.length != 0) {
            if (ArgsUtils.getIntValue(args[0]) != 0) {
                port = ArgsUtils.getIntValue(args[0]);
            }
        }

        this.port = port;


        /**
         * 启动服务
         */
        startServer(port);

        /**
         * 注册服务到ZK
         */
        registerServers(port);


        /**
         * 注册关机钩子
         */
        ShutdownHook.registerShutdownHook(port);


        System.out.println("-------------------------Netty server has started at port :" + port + " --------------------------");

    }


    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    public void startServer(int port) {
        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();

        io.netty.bootstrap.ServerBootstrap serverBootstrap = new io.netty.bootstrap.ServerBootstrap();
        serverBootstrap.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline pipeline = ch.pipeline();
                        //解决粘包/半包,根据消息长度自动拆包

                        ch.pipeline().addLast(new LengthFieldBasedFrameDecoder(65535, 0, 2, 0, 2));

                        pipeline.addLast(new StringEncoder());
                        pipeline.addLast(new RpcDecoder(RpcRequest.class, new FastJsonSerializer()));

                        //解决粘包/半包问题附加消息长度在消息头部
                        ch.pipeline().addLast(new LengthFieldPrepender(2));
                        pipeline.addLast(new ServiceHandlerAdapter(applicationContext, port));

                    }
                });
        try {
            //绑定端口,同步等待成功
            serverBootstrap.bind(port).sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }


    private void registerServers(int port) {

        try {
            String node = IpUtils.getAppConnectedAddress(port);
            String nodePath = "/" + node;
            CuratorFramework zkClient = ZkUtils.getZkClient();
            Stat stat = zkClient.checkExists().forPath(nodePath);
            if (stat != null && stat.getEphemeralOwner() > 0) {
                System.out.println("Node path already exists");
                return;
            }
            zkClient.create()
                    .creatingParentsIfNeeded()
                    .withMode(CreateMode.EPHEMERAL)
                    .forPath(nodePath, "0".getBytes());
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    public int getPort() {
        return port;
    }


}
